package com.mongoosehome.web.tag;

import java.util.Date;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.mongoosehome.web.util.DateTimeUtils;
import com.mongoosehome.web.util.StringUtils;

/**
 * JSP Tag 用于时间转换
 */
public class TimeTag extends TagSupport {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    Logger logger = LogManager.getLogger(TimeTag.class);
    private String time = "";       // time long
    private String timeformat = "";
    public static final long ONE_DAY_TIME = 1000 * 60 * 60 * 24;				//一天的时间值
    public static final long ONE_HOUR_TIME = 1000 * 60 * 60;				//一小时的时间值

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getTimeformat() {
        return timeformat;
    }

    public void setTimeformat(String timeformat) {
        this.timeformat = timeformat;
    }

    @Override
    public int doStartTag() throws JspException {
        if (null == this.time || this.time.length() == 0) {
            return Tag.SKIP_BODY;
        }

        try {
            Date now = new Date();
            long dateLong = Long.parseLong(this.time) * 1000;
            //dateLong = dateLong - (61 * 1000);	//解决刚刚发表完，显示0分钟前发表的问题
            dateLong -= (61 * 1000);	//解决刚刚发表完，显示0分钟前发表的问题
            Date date = new Date(dateLong);
            long nowTime = now.getTime();
            long scrip = nowTime - dateLong;
            JspWriter jspwriter = pageContext.getOut();
            if (scrip <= ONE_DAY_TIME) {
                if (scrip <= ONE_HOUR_TIME) {
                    jspwriter.print((scrip / (1000 * 60)) + "分钟前");
                } else {
                    jspwriter.print((scrip / (1000 * 60 * 60)) + "小时前");
                }
            } else {
                if (StringUtils.isFine(timeformat)) {
                    jspwriter.print(DateTimeUtils.formatDateTime(date, timeformat));
                } else {
                    jspwriter.print(DateTimeUtils.formatDateTime(date, "yyyy-MM-dd"));
                }

            }
            return Tag.SKIP_BODY;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new JspTagException(ex.getMessage());
        }
    }
}
